import {Component, ElementRef, OnDestroy, OnInit, TemplateRef} from "@angular/core";
import {NzMessageService} from "ng-zorro-antd";
import {FetchService} from "../../../../core/net/fetch.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Topology, Rect} from 'topology-core';
import * as _ from 'lodash';
import {Options} from 'topology-core/options';
import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser";
import {Router} from "@angular/router";
import {NzModalRef, NzModalService} from "ng-zorro-antd/modal";

@Component({
  selector: 'app-emergency-qxq',
  templateUrl: './emergency-qxq.component.html',
  styleUrls: ['../emergency-dispatch-common.scss', './emergency-qxq.component.scss']
})

export class EmergencyQxqComponent implements OnInit, OnDestroy {
  manageId = JSON.parse(localStorage.userInfo).manageId;
  selectedValue = '1';
  centerTableData = [];
  canvas: Topology;
  canvasOptions: Options = {};
  rect: Rect;
  hoverItem = {
    top: '0px',
    left: '0px',
    alertLevel: '-',
    waterLevel: '-',
    limitTraffic: '-',
    flow: '-'
  };
  infoShow = false;
  glcData;
  pptnrList = [];

  // 文件预览
  tplModal: NzModalRef;
  fileSrc = '';
  fileId = '';

  // gate		闸门
  // gate_out 	退水闸
  // pump		泵站
  // ZZ			水位站
  // ZQ			水文站
  // text_h		水位
  // text_q		流量

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private fetchService: FetchService,
    private el: ElementRef,
    private router: Router,
    private modal: NzModalService,
    private sanitizer: DomSanitizer
  ) {
    if (this.manageId == '10001') {
      this.selectedValue = '2';
    } else {
      this.selectedValue = this.manageId;
    }
  }

  ngOnInit(): void {
    window.addEventListener('resize', this.debounce(() => {
      this.onResize();
    }, 500));
    this.getHhsqTableData();
    this.getMapData();
  }

  ngOnDestroy(): void {
    this.canvas.destroy();
  }

  // 防抖函数
  debounce(func, wait?, immediate?): any {
    let timeout;
    return () => {
      const context = this;
      const args = arguments;
      const later = () => {
        timeout = null;
        if (!immediate) {
          func.apply(context, args);
        }
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) {
        func.apply(context, args);
      }
    };
  }

  // 窗口变化
  onResize() {
    console.log('windonw is resize');
    const h = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().height;
    const w = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().width; // 设置画布
    this.rect = this.canvas.getRect();
    if (this.rect.width / this.rect.height > w / h) {
      this.canvas.scale(w / this.rect.width * 0.98);
    } else {
      this.canvas.scale(h / this.rect.height * 0.95);
    }
    this.canvas.translate(w / 2 - this.rect.center.x, h / 2 - this.rect.center.y);
  }

  getMapData(): void {
    this.fetchService.post<any>('schedule/actualDispatchMonData/data', {manageId: this.selectedValue}).subscribe(r => {
      this.glcData = r;
      this.fetchService.get<any>('assets/data/glcnew/' + this.selectedValue + '.json').subscribe(res => {
        const pens = res.pens;
        // 数据处理
        this.glcData.map(feature => {
          for (const pen of pens) {
            // 修改闸门颜色
            if (pen.data.cid == feature.objId) {
              pen.image = '/yjq_web/assets/images/ght/newicons/' + feature.objType + feature.status + '.png';
            }
            // 修改q
            if (pen.data.cid == `${feature.objId}q`) {
              pen.text = feature.flow ? feature.flow + 'm³/s' : '-m³/s';
            }
            // 修改h
            if (pen.data.cid == `${feature.objId}h`) {
              pen.text = feature.waterLevel ? feature.waterLevel + 'm' : '-m';
            }
          }
        });

        if (this.canvas) {
          // 重置画布数据
          this.canvas.open({
            id: '',
            version: '',
            name: 'new空白文件',
            desc: '',
            image: '',
            userId: '',
            class: '',
            component: false,
            shared: false
          });
        } else {
          // 创建画布
          this.canvasOptions.on = this.onMouseEvent.bind(this);
          this.canvas = new Topology('topology-canvas', this.canvasOptions);
        }
        this.canvas.open(res);

        // 设置画布
        this.onResize();
      });
    });
  }

  // 概化图元素事件
  onMouseEvent(event: string, node: any) {
    if (event === 'moveInNode') {
      if (node.data != '' && (['ZZ', 'ZQ', 'gate', 'gate_out'].indexOf(node.data.type) > -1)) {
        console.log(event, node);
        this.infoShow = true;
        const yArr = [node.rotatedAnchors[0].y, node.rotatedAnchors[1].y, node.rotatedAnchors[2].y, node.rotatedAnchors[3].y];
        const featureH = _.max(yArr) - _.min(yArr);
        console.log(featureH);
        this.hoverItem.top = (node.rect.center.y - 120 - featureH / 2 + 10) + 'px';
        this.hoverItem.left = (node.rect.center.x - 76) + 'px';
        const nodeId = node.data.cid;
        this.glcData.map(item => {
          if (item.objId == nodeId) {
            this.hoverItem.alertLevel = item.alertLevel || '-';
            this.hoverItem.flow = item.flow || '-';
            this.hoverItem.limitTraffic = item.limitTraffic || '-';
            this.hoverItem.waterLevel = item.waterLevel || '-';
          }
        });
      }
    }
    if (event === 'moveOutNode') {
      this.infoShow = false;
    }
    if (event === 'node') {
      // alert(node.data.name + '被点击了');
    }
  }

  getHhsqTableData(): void {
    this.fetchService.post<any>('schedule/wrsActualDispatchApply/staticData', {manageId: this.selectedValue}).subscribe(res => {
      this.centerTableData = res;
    });

    this.fetchService.post<any>('intake/wrsPptnR/ddList', {description: 3}).subscribe(res => {
      this.pptnrList = res.data;
    });
  }

  goBack(): void {
    this.router.navigate([`/realtime-control/emergency-home`]);
  }

  viewFile(tplContent: TemplateRef<{}>): void {
    const that = this;
    this.fileSrc = `${(window as any).environment.apiBaseUrl}comm/file/view/b11c6f16453940f88ff398e5b025cd73`;
    this.tplModal = this.modal.create({
      nzTitle: '文件预览',
      nzContent: tplContent,
      nzWidth: 1100,
      nzStyle: { top: '20px' },
      nzClassName: 'custom-modal',
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: true,
      nzOnCancel(): void {
        that.destroyModal();
      }
    });
  }

  destroyModal() {
    this.tplModal.destroy();
  }
}
